package com.zzyl.framework.aspectj;

import com.zzyl.common.annotation.Cacheable;
import com.zzyl.common.annotation.DeleteCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 缓存添加，删除切面
 */
@Component
@Aspect
public class RedisAspect {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 添加缓存
     * @param joinPoint
     * @param cacheable
     * @return
     * @throws Throwable
     */
    @Around("@annotation(cacheable)")
    public Object addRedis(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws Throwable {
        //先查询缓存
        Object cacheVal = redisTemplate.opsForValue().get(cacheable.key());
        if (cacheVal != null) {
            return cacheVal;
        }
        //如果缓存不存在，则查询数据库，返回值并添加缓存
        Object result = joinPoint.proceed();
        redisTemplate.opsForValue().set(cacheable.key(), result);
        return result;
    }


    /**
     * 删除缓存
     */
    @Around("@annotation(deleteCache)")
    public Object deleteCache(ProceedingJoinPoint joinPoint, DeleteCache deleteCache) throws Throwable {
        Object count = joinPoint.proceed();
        if ((int)count > 0) {
            redisTemplate.delete(deleteCache.key());
        }
        return count;
    }
}
